﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Web.Http;

namespace Magicodes.WeiChat.Infrastructure.WebApiExtension.Results
{
    /// <summary>
    /// 获取WebApi结果
    /// </summary>
    public class ClientApiResult : IHttpActionResult
    {
        private readonly ApiController _controller;
        public string BaseUrl { get; set; }
        public string ApiUrl { get; set; }
        public string ContentType { get; set; }

        public ApiTypes ApiType { get; set; }
        public object Data { get; set; }

        public ClientApiResult(ApiController controller, string baseUrl, string apiUrl, ApiTypes apiType = ApiTypes.Get, object data = null, string contentType = "application/json")
        {
            if (baseUrl == null)
            {
                throw new ArgumentNullException("baseUrl");
            }

            if (apiUrl == null)
            {
                throw new ArgumentNullException("apiUrl");
            }

            this.BaseUrl = baseUrl;
            this.ApiUrl = apiUrl;
            this.ContentType = contentType;
            this.ApiType = apiType;
            this.Data = data;
            _controller = controller;
        }
        public HttpRequestMessage Request
        {
            get { return _controller.Request; }
        }

        public async Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
        {
            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri(this.BaseUrl);
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                switch (ApiType)
                {
                    case ApiTypes.Get:
                        return await client.GetAsync(this.ApiUrl);
                    case ApiTypes.Post:
                        return await client.PostAsJsonAsync(this.ApiUrl, this.Data);
                    case ApiTypes.Put:
                        return await client.PutAsJsonAsync(this.ApiUrl, this.Data);
                    case ApiTypes.Delete:
                        return await client.DeleteAsync(this.ApiUrl);
                    default:
                        break;
                }
                return await client.GetAsync(this.ApiUrl);
                //return await response.Content.ReadAsHttpResponseMessageAsync();
            }
        }
    }
}
